package cn.yuanqiao.archive.wenjianzhengli.utils;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Iterator;
import java.util.Map;

/**
 * @author zjj
 * @date 2023/7/18
 */
public class CustomSheetWriteHandler  implements SheetWriteHandler {

    private Map<Integer,String []> mapList;

    public CustomSheetWriteHandler(Map<Integer,String []> mapList) {
        this.mapList = mapList;
    }

    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        //log.info("第{}个Sheet写入成功。", context.getWriteSheetHolder().getSheetNo());

        // 区间设置 第一列第一行和第二行的数据。由于第一行是头，所以第一、二行的数据实际上是第二三行
        //CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 2, 0, 0);
        Iterator<Map.Entry<Integer, String []>> iterator = mapList.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, String []> entry = iterator.next();
            CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 100, entry.getKey(), entry.getKey());
            DataValidationHelper helper = context.getWriteSheetHolder().getSheet().getDataValidationHelper();
            DataValidationConstraint constraint = helper.createExplicitListConstraint(entry.getValue());
            DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
            context.getWriteSheetHolder().getSheet().addValidationData(dataValidation);
        }
    }
}
